<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/lonie233/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/lonie233/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/lonie233/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/lonie233/images/logo.svg" color="#222">

<link rel="stylesheet" href="/lonie233/css/main.css">


<link rel="stylesheet" href="/lonie233/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lonie233.gitee.io","root":"/lonie233/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="摘要在上边我们介绍了Kafka涉及到的基本概念，消息交付语义，高可靠相关原理，现在开始向下研究一些细节设计以及源码。本文主要讲述Producer和Consumer在生产&#x2F;消费时是如何确定分区的 如有问题，欢迎gitee 提 issue，共同进步">
<meta property="og:type" content="article">
<meta property="og:title" content="分区机制">
<meta property="og:url" content="https://lonie233.gitee.io/2021/04/06/kafka-specific-partition/index.html">
<meta property="og:site_name" content="Welcome">
<meta property="og:description" content="摘要在上边我们介绍了Kafka涉及到的基本概念，消息交付语义，高可靠相关原理，现在开始向下研究一些细节设计以及源码。本文主要讲述Producer和Consumer在生产&#x2F;消费时是如何确定分区的 如有问题，欢迎gitee 提 issue，共同进步">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-04-06T03:11:11.000Z">
<meta property="article:modified_time" content="2021-12-16T06:31:33.599Z">
<meta property="article:author" content="lonie">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://lonie233.gitee.io/2021/04/06/kafka-specific-partition/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>分区机制 | Welcome</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-193107295-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-193107295-1');
      }
    </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/lonie233/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Welcome</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/lonie233/" rel="section"><i class="home  //首页 fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/lonie233/about/" rel="section"><i class="user  //关于 fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/lonie233/tags/" rel="section"><i class="tags  //标签 fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/lonie233/categories/" rel="section"><i class="th   //分类 fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/lonie233/archives/" rel="section"><i class="archive //归档 fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-schedule">

    <a href="/lonie233/schedule/" rel="section"><i class="calendar   //日程表 fa-fw"></i>日程表</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/lonie233/sitemap.xml" rel="section"><i class="sitemap   //站点地图 fa-fw"></i>站点地图</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    

  <a href="https://gitee.com/lonie233/lonie233" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lonie233.gitee.io/2021/04/06/kafka-specific-partition/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/lonie233/images/avatar.jpg">
      <meta itemprop="name" content="lonie">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Welcome">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          分区机制
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-04-06 11:11:11" itemprop="dateCreated datePublished" datetime="2021-04-06T11:11:11+08:00">2021-04-06</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-12-16 14:31:33" itemprop="dateModified" datetime="2021-12-16T14:31:33+08:00">2021-12-16</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/lonie233/categories/Kafka/" itemprop="url" rel="index"><span itemprop="name">Kafka</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>1.2k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>1 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="摘要"><a href="#摘要" class="headerlink" title="摘要"></a>摘要</h3><p>在上边我们介绍了Kafka涉及到的基本概念，消息交付语义，高可靠相关原理，现在开始向下研究一些细节设计以及源码。本文主要讲述Producer和Consumer在生产/消费时是如何<strong>确定分区</strong>的</p>
<p>如有问题，欢迎gitee 提 issue，共同进步</p>
<a id="more"></a>

<h3 id="Producer-分区机制"><a href="#Producer-分区机制" class="headerlink" title="Producer 分区机制"></a>Producer 分区机制</h3><p>关于分区的概念，我们在基础知识阶段就已经讲过了，不再赘述。Kafka能实现这么大吞吐量，主要就是在能够高速的写入，而在分布式系统里，为了实现这一点，就一定需要负载均衡，将集群的压力分摊到各个节点上，避免出现倾斜，导致单点。</p>
<p>所以，Producer的分区其实就是一个负载均衡的过程，也是Kafka实现高吞吐的基础。Kafka Producer 支持如下的分区策略</p>
<ol>
<li><p>轮询</p>
<ol>
<li>就像名字一样，轮流把消息写入到各个分区，这样能保证各个分区内的消息数量都非常节点，实现集群的平衡，也是Kafka默认的策略，没有特殊需求，不建议修改</li>
</ol>
</li>
<li><p>随机</p>
<ol>
<li><p>获取分区数量</p>
</li>
<li><p>生成随机数，指定分区的Index，然后写入</p>
</li>
<li><pre><code class="java">List partitions = cluster.partitionsForTopic(topic);
return ThreadLocalRandom.current().nextInt(partitions.size());
</code></pre>
</li>
</ol>
</li>
<li><p>按Key保存</p>
<ol>
<li>发送消息的时候指定Key，相同的Key会计算hash值然后放到同一个分区内。</li>
<li>kafka 发送消息的时候默认是轮询，如果指定了Key，则会按key存储</li>
</ol>
</li>
<li><p>自定义分区策略</p>
<ol>
<li>自己实现Partitioner.class，然后在Producer内指定分区类</li>
</ol>
</li>
</ol>
<p>以上就是Kafka自带及支持的分区策略</p>
<h3 id="Consumer-分区机制"><a href="#Consumer-分区机制" class="headerlink" title="Consumer 分区机制"></a>Consumer 分区机制</h3><p>Consumer 消费分区机制是由kafka内置的，因为上传的时候的分区了，所以消费的时候也要分区。Consumer还有一个 Consumer Group 的概念。Consumer Group 是为了屏蔽Consumer 实例设计的，一个group内有多个实例，这样，某一个实例挂掉之后，能迅速且换消费实例。一个分区只能被一个消费者实例消费。</p>
<ol>
<li><p>Range</p>
<ol>
<li><p>range分配策略针对的是主题（PS：也就是说，这里所说的分区指的某个主题的分区，消费者值的是订阅这个主题的消费者组中的消费者实例）</p>
</li>
<li><p>首先，将分区按数字顺序排行序，消费者按消费者名称的字典序排好序</p>
</li>
<li><p>然后，用分区总数除以消费者总数。如果能够除尽，则皆大欢喜，平均分配；若除不尽，则位于排序前面的消费者将多负责一个分区</p>
</li>
</ol>
<p>例如，假设有两个消费者C0和C1，两个主题t0和t1，并且每个主题有3个分区，分区的情况是这样的：t0p0，t0p1，t0p2，t1p0，t1p1，t1p2</p>
<p>那么，基于以上信息，最终消费者分配分区的情况是这样的：</p>
<p>C0: [t0p0, t0p1, t1p0, t1p1]</p>
<p>C1: [t0p2, t1p2]</p>
</li>
<li><p>轮询</p>
<ol>
<li>轮询着把Topic的分区分配给所有Consumer</li>
</ol>
</li>
<li><p>固定分配</p>
<ol>
<li>即尽量不动已有的分配策略</li>
</ol>
</li>
</ol>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/lonie233/2021/04/01/kafka-classic-question/" rel="prev" title="kafka经典问题">
      <i class="fa fa-chevron-left"></i> kafka经典问题
    </a></div>
      <div class="post-nav-item">
    <a href="/lonie233/2021/04/11/design-component/" rel="next" title="设计-实现一个xxx 组件">
      设计-实现一个xxx 组件 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%91%98%E8%A6%81"><span class="nav-number">1.</span> <span class="nav-text">摘要</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Producer-%E5%88%86%E5%8C%BA%E6%9C%BA%E5%88%B6"><span class="nav-number">2.</span> <span class="nav-text">Producer 分区机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Consumer-%E5%88%86%E5%8C%BA%E6%9C%BA%E5%88%B6"><span class="nav-number">3.</span> <span class="nav-text">Consumer 分区机制</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="lonie"
      src="/lonie233/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">lonie</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/lonie233/archives/">
        
          <span class="site-state-item-count">14</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/lonie233/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/loniecc" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;loniecc" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huzeming2019@outlook.com" title="E-Mail → mailto:huzeming2019@outlook.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lonie</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">12k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11 分钟</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lonie233/lib/anime.min.js"></script>
  <script src="/lonie233/lib/velocity/velocity.min.js"></script>
  <script src="/lonie233/lib/velocity/velocity.ui.min.js"></script>

<script src="/lonie233/js/utils.js"></script>

<script src="/lonie233/js/motion.js"></script>


<script src="/lonie233/js/schemes/pisces.js"></script>


<script src="/lonie233/js/next-boot.js"></script>




  















  

  

</body>
</html>
